<template>
  <div class="game-container">
    <!-- 连接错误状态 -->
    <div v-if="connectionError" class="error-overlay">
      <div class="error-content">
        <h2>连接失败</h2>
        <p>{{ connectionError }}</p>
        <button @click="reconnect" class="retry-btn">重新连接</button>
      </div>
    </div>

    <!-- 游戏界面 -->
    <div v-else class="game-interface">
      <!-- 主游戏区域 -->
      <main class="game-main">
        <!-- 左侧面板 -->
        <aside class="left-sidebar">
          <!-- 排行榜 -->
          <div class="leaderboard">
            <h3 class="panel-title">排行榜</h3>
            <div class="leaderboard-list">
              <div
                v-for="(player, index) in rankedPlayers"
                :key="player.PlayerId"
                class="leaderboard-item"
                :class="{
                  'current-player': player.PlayerId === effectivePlayerId,
                  'dead-player': !player.IsAlive
                }"
              >
                <div class="player-rank">{{ index + 1 }}</div>
                <div
                  class="player-avatar"
                  :style="{ backgroundColor: player.Color }"
                ></div>
                <div class="player-info">
                  <div class="player-name">{{ player.Username }}</div>
                  <div class="player-score">{{ formatArea(player.TotalTerritoryArea) }}</div>
                </div>
                <div class="player-percent">{{ ((player.TotalTerritoryArea / (Math.PI * gameState.MapRadius * gameState.MapRadius)) * 100).toFixed(1) }}%</div>
              </div>
            </div>
          </div>

          <!-- 左侧小地图 -->
          <div class="left-minimap-container">
            <h3 class="panel-title">地图</h3>
            <div class="left-minimap">
              <canvas
                ref="leftMiniMapCanvas"
                :width="160"
                :height="160"
                class="left-minimap-canvas"
                @click="handleMinimapClick"
              ></canvas>
            </div>
          </div>
        </aside>

        <!-- 游戏画布区域 -->
        <section class="canvas-area">
          <LineDrawingCanvas
            ref="canvasRef"
            :gameState="gameState"
            :playerId="effectivePlayerId"
            :gameService="lineDrawingGameService"
            class="main-canvas"
            @error="handleGameError"
          />
        </section>
      </main>
    </div>

    <!-- 游戏错误提示 -->
    <div v-if="gameError" class="error-toast">
      <span>{{ gameError }}</span>
      <button @click="gameError = ''" class="toast-close">×</button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { lineDrawingGameService } from '@/services/lineDrawingGameService'
import LineDrawingCanvas from '@/components/LineDrawingCanvas.vue'

// Props
const props = defineProps({
  gameId: {
    type: String,
    required: true
  },
  playerId: {
    type: String,
    required: false,
    default: ''
  },
  playerName: {
    type: String,
    required: false,
    default: ''
  }
})

// Router and stores
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const connectionError = ref('')
const gameError = ref('')
const showRanking = ref(false)
const showSettings = ref(false)
const connectionProgress = ref(0)
const connectionMessage = ref('连接中...')
const totalExpectedPlayers = ref(8)
const leftMiniMapCanvas = ref(null)
const canvasRef = ref(null)

// 计算后的玩家ID，确保在用户信息异步初始化后也能更新
const effectivePlayerId = computed(() => {
  // 优先使用userStore中的真实用户信息，而不是URL参数
  const storeUserId = userStore.userInfo?.id
  const propPlayerId = props.playerId
  
  console.log('计算effectivePlayerId - storeUserId:', storeUserId, 'propPlayerId:', propPlayerId)
  
  // 如果userStore有用户ID，优先使用它
  if (storeUserId) {
    return storeUserId
  }
  
  // 否则使用props中的playerId作为后备
  return propPlayerId || ''
})

// 游戏状态 - 使用reactive确保深度响应式
const gameState = reactive({
  Status: 'Playing', // 直接设置为游戏中状态
  Players: [],
  PowerUps: [],
  MaxPlayers: 8,
  MapWidth: 2000,  // 圆形地图直径2000像素
  MapHeight: 2000,
  MapRadius: 1000, // 圆形地图半径1000像素
  TimeLeft: 300,
  Settings: {
    Duration: 300,
    EnablePowerUps: true,
    GameMode: 'classic' // 默认经典模式
  }
})

const gameSettings = reactive({
  duration: 300,
  mapSize: 2000, // 圆形地图直径
  enablePowerUps: true,
  gameMode: 'classic'
})

// 排行榜数据
const rankings = ref([])

// 游戏状态计算
const uiStatus = computed(() => {
  const s = (gameState.Status || '').toString().toLowerCase()
  if (s.includes('waiting')) return 'waiting'
  if (s.includes('playing')) return 'playing'
  if (s.includes('finished') || s.includes('end')) return 'finished'
  return 'playing' // 默认为游戏中状态
})

const isGameHost = computed(() => {
  const currentPlayer = gameState.Players?.find(p => p.PlayerId === effectivePlayerId.value)
  return currentPlayer?.IsHost || false
})

const canStartGame = computed(() => {
  return gameState.Players?.length >= 2
})

const alivePlayersCount = computed(() => {
  return gameState.Players?.filter(p => p.IsAlive).length || 0
})

const totalPlayersCount = computed(() => {
  return gameState.Players?.length || 0
})

const timeLeft = computed(() => {
  return gameState.TimeLeft || 0
})

const connectedPlayersCount = computed(() => {
  return gameState.Players?.filter(p => p.IsConnected !== false).length || 0
})

const allPlayersConnected = computed(() => {
  const players = gameState.Players || []
  const expectedCount = totalExpectedPlayers.value || players.length
  return players.length > 0 && players.length >= expectedCount && 
         players.every(p => p.IsConnected !== false)
})

// 排行榜计算 - 按领地面积排序
const rankedPlayers = computed(() => {
  console.log('计算 rankedPlayers - gameState.Players:', gameState.Players)
  if (!gameState.Players || !Array.isArray(gameState.Players) || gameState.Players.length === 0) {
    console.log('rankedPlayers: gameState.Players 为空或无效，返回空数组')
    return []
  }
  
  console.log('rankedPlayers: 玩家数量:', gameState.Players.length)
  gameState.Players.forEach((player, index) => {
    // 兼容CamelCase和PascalCase字段
    const playerId = player.playerId || player.PlayerId
    const username = player.username || player.Username
    const isAlive = player.isAlive !== undefined ? player.isAlive : player.IsAlive
    const territoryArea = player.totalTerritoryArea || player.TotalTerritoryArea
    console.log(`rankedPlayers: 玩家${index + 1} - PlayerId: ${playerId}, Username: ${username}, IsAlive: ${isAlive}, TotalTerritoryArea: ${territoryArea}`)
  })
  
  const sorted = [...gameState.Players].sort((a, b) => {
    // 兼容CamelCase字段排序
    const aArea = a.totalTerritoryArea || a.TotalTerritoryArea || 0
    const bArea = b.totalTerritoryArea || b.TotalTerritoryArea || 0
    const aKills = a.killCount || a.KillCount || 0
    const bKills = b.killCount || b.KillCount || 0
    
    // 先按领地面积排序，再按击杀数排序
    if (bArea !== aArea) {
      return bArea - aArea
    }
    return bKills - aKills
  })
  
  console.log('rankedPlayers: 排序后的玩家列表:', sorted.map(p => ({ 
    Username: p.username || p.Username, 
    TotalTerritoryArea: p.totalTerritoryArea || p.TotalTerritoryArea, 
    KillCount: p.killCount || p.KillCount 
  })))
  return sorted
})

const currentPlayerStats = computed(() => {
  if (!gameState.Players || !Array.isArray(gameState.Players) || gameState.Players.length === 0) {
    console.log('计算 currentPlayerStats: Players数组为空')
    return undefined
  }
  
  // 兼容CamelCase字段查找玩家
  const result = gameState.Players.find(p => 
    (p.playerId === effectivePlayerId.value) || (p.PlayerId === effectivePlayerId.value)
  )
  console.log('计算 currentPlayerStats:', {
    effectivePlayerId: effectivePlayerId.value,
    players: gameState.Players.map(p => ({ 
      playerId: p.playerId || p.PlayerId, 
      username: p.username || p.Username 
    })),
    found: result,
    isAlive: result?.isAlive !== undefined ? result.isAlive : result?.IsAlive
  })
  return result
})

// 游戏初始化
const initializeGame = async () => {
  try {
    connectionError.value = ''
    console.log('=== 开始初始化游戏 ===')
    
    // 检查用户认证
    if (!userStore.userInfo || !userStore.userInfo.id || !userStore.token) {
      throw new Error('用户未登录或token无效')
    }
    
    // 获取玩家信息
    const playerId = props.playerId || userStore.userInfo.id
    const playerName = props.playerName || userStore.userInfo.username
    
    console.log('初始化游戏参数:', {
      gameId: props.gameId,
      playerId,
      playerName,
      token: userStore.token?.substring(0, 20) + '...'
    })
    console.log('当前用户信息:', userStore.userInfo)
    
    // 连接游戏服务
    console.log('连接游戏服务...')
    await lineDrawingGameService.connect(userStore.token)
    console.log('游戏服务连接成功')
    
    // 设置游戏事件监听器
    setupGameEventListeners()
    
    // 加入游戏房间
    console.log('加入游戏房间...')
    await lineDrawingGameService.joinGame(props.gameId, playerId, playerName)
    console.log('成功加入游戏房间')
    
    // 请求游戏状态
    console.log('请求游戏状态...')
    await lineDrawingGameService.requestGameState()
    console.log('游戏状态请求发送')
    
    // 更新连接进度
    updateConnectionProgress()
  } catch (error) {
    console.error('游戏初始化失败:', error)
    connectionError.value = error.message || '连接失败'
  }
}

// 设置游戏事件监听器
const setupGameEventListeners = () => {
  lineDrawingGameService.onGameStateUpdate = (data) => {
    console.log('🎮 [Game] 收到游戏状态更新:', data)
    console.log('🔍 [Debug] 数据类型:', typeof data)
    console.log('🔍 [Debug] 数据键值:', Object.keys(data))
    console.log('🔍 [Debug] 完整数据结构:', JSON.stringify(data, null, 2))
    console.log('🔍 [Debug] Players字段:', data.Players)
    console.log('🔍 [Debug] players字段(小写):', data.players)
    console.log('🔍 [Debug] Players是否为数组:', Array.isArray(data.Players))
    console.log('🔍 [Debug] players是否为数组:', Array.isArray(data.players))
    console.log('🔍 [Debug] Players长度:', data.Players?.length)
    console.log('🔍 [Debug] players长度:', data.players?.length)
    
    if (data && typeof data === 'object') {
      // 处理CamelCase命名映射
      const mappedData = {
        ...data,
        Players: data.players || data.Players,
        PowerUps: data.powerUps || data.PowerUps,
        MapWidth: data.mapWidth || data.MapWidth,
        MapHeight: data.mapHeight || data.MapHeight,
        MaxPlayers: data.maxPlayers || data.MaxPlayers,
        StartTime: data.startTime || data.StartTime,
        EndTime: data.endTime || data.EndTime,
        EnablePowerUps: data.enablePowerUps || data.EnablePowerUps,
        TotalTerritoryArea: data.totalTerritoryArea || data.TotalTerritoryArea
      }
      
      // 更新游戏状态，保持响应式
      Object.keys(mappedData).forEach(key => {
        if (gameState.hasOwnProperty(key)) {
          gameState[key] = mappedData[key]
        }
      })
      
      // 特别处理Players数组
      const players = data.players || data.Players
      if (players && Array.isArray(players)) {
        gameState.Players.splice(0, gameState.Players.length, ...players)
        console.log('🎮 [Game] Players更新完成, 当前玩家数量:', gameState.Players.length)
        
        // 记录每个玩家的状态和轨迹信息
        gameState.Players.forEach((player, index) => {
          const pathCount = (player.currentPath || player.CurrentPath)?.length || 0
          const isDrawing = player.isDrawing || player.IsDrawing
          console.log(`🎮 [Game] 玩家${index + 1}: ${player.username || player.Username} (ID: ${player.playerId || player.PlayerId}), IsAlive: ${player.isAlive || player.IsAlive}, IsDrawing: ${isDrawing}, PathCount: ${pathCount}`)
        })
      } else {
        console.warn('🔍 [Debug] Players数据无效或为空')
      }
      
      // 处理道具更新
      const powerUps = data.powerUps || data.PowerUps
      if (powerUps && Array.isArray(powerUps)) {
        gameState.PowerUps.splice(0, gameState.PowerUps.length, ...powerUps)
      }
      
      // 更新排行榜数据（如果存在）
      if (data.Rankings && Array.isArray(data.Rankings)) {
        rankings.value = data.Rankings
        console.log('🏆 [Game] 排行榜更新:', data.Rankings)
      }
      
      // 更新连接进度
      updateConnectionProgress()
      
      // 渲染左侧小地图
      nextTick(() => {
        renderLeftMinimap()
      })
    } else {
      console.warn('🎮 [Game] 收到无效的游戏状态数据:', data)
    }
  }
  
  lineDrawingGameService.onGameStarted = (data) => {
    console.log('🎮 [Game] 游戏开始:', data)
  }
  
  lineDrawingGameService.onPlayerRespawned = (data) => {
    console.log('🎮 [Game] 玩家复活:', data)
    
    // 查找并更新玩家状态
    const player = gameState.Players.find(p => p.PlayerId === data.PlayerId)
    if (player) {
      player.IsAlive = true
      player.CurrentPosition = data.SpawnPosition
      player.IsInSafeZone = true
      player.InvincibilityEndTime = new Date(Date.now() + (data.InvincibilityTimeMs || 5000))
      console.log('🎮 [Game] 玩家', data.PlayerId, '复活状态已更新')
    }
  }
  
  lineDrawingGameService.onGameFinished = (data) => {
    console.log('🎮 [Game] 游戏结束:', data)
  }
  
  lineDrawingGameService.onPlayerJoined = (data) => {
    console.log('🎮 [Game] 玩家加入:', data)
    updateConnectionProgress()
  }
  
  lineDrawingGameService.onPlayerLeft = (data) => {
    console.log('🎮 [Game] 玩家离开:', data)
    updateConnectionProgress()
  }
  
  lineDrawingGameService.onPlayerConnectionUpdate = (data) => {
    console.log('🎮 [Game] 玩家连接状态更新:', data)
    
    // 更新玩家连接状态
    const player = gameState.Players.find(p => p.PlayerId === data.PlayerId)
    if (player) {
      player.IsConnected = data.IsConnected
    }
    updateConnectionProgress()
  }
  
  // ✅ 添加排行榜更新事件监听
  lineDrawingGameService.onRankingUpdate = (data) => {
    console.log('🏆 [Game] 排行榜更新事件:', data)
    
    // 处理CamelCase命名映射 - 排行榜数据可能在rankings字段中
    const rankingData = data?.rankings || data
    
    if (rankingData && Array.isArray(rankingData)) {
      // 映射CamelCase字段名
      const mappedRankings = rankingData.map(item => ({
        PlayerId: item.playerId || item.PlayerId,
        Username: item.username || item.Username,
        TotalTerritoryArea: item.totalTerritoryArea || item.TotalTerritoryArea,
        Rank: item.rank || item.Rank,
        IsAlive: item.isAlive || item.IsAlive,
        KillCount: item.killCount || item.KillCount,
        DeathCount: item.deathCount || item.DeathCount
      }))
      
      // 更新排行榜数据
      rankings.value = mappedRankings
      
      // 同步更新Players数组中的玩家数据
      mappedRankings.forEach(rankingPlayer => {
        const player = gameState.Players.find(p => (p.playerId || p.PlayerId) === rankingPlayer.PlayerId)
        if (player) {
          // 保持玩家的存活状态不被覆盖
          const originalIsAlive = player.isAlive || player.IsAlive
          const originalInvincibilityEndTime = player.invincibilityEndTime || player.InvincibilityEndTime
          const originalIsConnected = player.isConnected || player.IsConnected
          
          // 更新其他数据 - 同时处理CamelCase和PascalCase
          player.PlayerId = player.PlayerId || rankingPlayer.PlayerId
          player.playerId = player.playerId || rankingPlayer.PlayerId
          player.Username = player.Username || rankingPlayer.Username
          player.username = player.username || rankingPlayer.Username
          player.TotalTerritoryArea = rankingPlayer.TotalTerritoryArea
          player.totalTerritoryArea = rankingPlayer.TotalTerritoryArea
          player.Rank = rankingPlayer.Rank
          player.rank = rankingPlayer.Rank
          player.KillCount = rankingPlayer.KillCount
          player.killCount = rankingPlayer.KillCount
          player.DeathCount = rankingPlayer.DeathCount
          player.deathCount = rankingPlayer.DeathCount
          
          // 保持原始状态
          player.IsAlive = originalIsAlive
          player.isAlive = originalIsAlive
          player.InvincibilityEndTime = originalInvincibilityEndTime
          player.invincibilityEndTime = originalInvincibilityEndTime
          player.IsConnected = originalIsConnected
          player.isConnected = originalIsConnected
          
          console.log('🏆 [Game] 玩家数据同步:', rankingPlayer.Username, 'IsAlive保持:', originalIsAlive, '面积更新:', rankingPlayer.TotalTerritoryArea)
        }
      })
      
      console.log('🏆 [Game] 排行榜同步完成, 玩家数量:', gameState.Players.length)
    } else {
      console.warn('🏆 [Game] 排行榜数据格式错误:', data)
    }
  }
  
  lineDrawingGameService.onMoveRejected = (data) => {
    console.log('[Game] 收到移动被拒绝事件，通知Canvas停止移动')
    // 通过ref引用直接调用Canvas的停止移动方法
    if (canvasRef.value && canvasRef.value.handleMoveRejected) {
      canvasRef.value.handleMoveRejected(data)
    }
  }
  
  lineDrawingGameService.onError = (message) => {
    gameError.value = message
  }
  
  lineDrawingGameService.onDisconnected = () => {
    connectionError.value = '连接已断开'
  }
}

// 连接进度更新
const updateConnectionProgress = () => {
  const connected = connectedPlayersCount.value
  const expected = totalExpectedPlayers.value
  
  if (expected > 0) {
    connectionProgress.value = Math.min((connected / expected) * 100, 100)
    connectionMessage.value = `已连接 ${connected}/${expected} 玩家`
  }
}

// 游戏设置更新
const updateGameSettings = async () => {
  if (!isGameHost.value) return
  
  try {
    // await lineDrawingGameService.updateGameSettings(gameSettings)
    console.log('游戏设置已更新:', gameSettings)
  } catch (error) {
    console.error('更新游戏设置失败:', error)
    gameError.value = '更新设置失败'
  }
}

// 开始游戏
const startGame = async () => {
  try {
    await lineDrawingGameService.startGame()
  } catch (error) {
    console.error('开始游戏失败:', error)
    gameError.value = '开始游戏失败'
  }
}

// 离开游戏
const leaveGame = async () => {
  try {
    await lineDrawingGameService.leaveGame()
    router.push('/lobby')
  } catch (error) {
    console.error('离开游戏失败:', error)
    gameError.value = '离开游戏失败'
  }
}

// 重新连接
const reconnect = () => {
  connectionError.value = ''
  initializeGame()
}

// 再次游戏
const playAgain = async () => {
  try {
    await lineDrawingGameService.restartGame()
  } catch (error) {
    console.error('重新开始游戏失败:', error)
    gameError.value = '重新开始失败'
  }
}

// 回到大厅
const backToLobby = () => {
  leaveGame()
}

// 处理游戏错误
const handleGameError = (error) => {
  gameError.value = error
}

// 时间格式化
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 面积格式化
const formatArea = (area) => {
  return Math.round(area).toLocaleString()
}

// 道具使用
const useItem = async (itemType) => {
  try {
    await lineDrawingGameService.usePowerUp(itemType)
  } catch (error) {
    console.error('使用道具失败:', error)
    gameError.value = '使用道具失败'
  }
}

// 键盘控制
const handleKeyPress = (event) => {
  switch (event.key.toLowerCase()) {
    case 'tab':
      event.preventDefault()
      // 切换小地图显示模式
      break
    case ' ':
    case 'space':
      event.preventDefault()
      // 短暂加速功能
      break
  }
}

// 小地图点击处理
const handleMinimapClick = (event) => {
  // 处理小地图点击，可以用于快速导航
  console.log('小地图点击:', event)
}

// 渲染左侧小地图
const renderLeftMinimap = () => {
  if (!leftMiniMapCanvas.value) return
  
  const canvas = leftMiniMapCanvas.value
  const ctx = canvas.getContext('2d')
  const size = 160
  const mapRadius = size / 2 - 2
  const centerX = size / 2
  const centerY = size / 2
  
  // 清空画布
  ctx.fillStyle = '#1a1a2e'
  ctx.fillRect(0, 0, size, size)
  
  // 绘制圆形地图背景
  const gradient = ctx.createRadialGradient(
    centerX, centerY, 0,
    centerX, centerY, mapRadius
  )
  gradient.addColorStop(0, '#2a2a4e')
  gradient.addColorStop(0.7, '#1e1e3f')
  gradient.addColorStop(1, '#16213e')
  
  ctx.fillStyle = gradient
  ctx.beginPath()
  ctx.arc(centerX, centerY, mapRadius, 0, Math.PI * 2)
  ctx.fill()
  
  // 绘制地图边界
  ctx.strokeStyle = '#ff6b6b'
  ctx.lineWidth = 2
  ctx.beginPath()
  ctx.arc(centerX, centerY, mapRadius, 0, Math.PI * 2)
  ctx.stroke()
  
  // 绘制玩家领地
  if (gameState.Players) {
    gameState.Players.forEach(player => {
      if (!player.Territories || player.Territories.length === 0) return
      
      ctx.fillStyle = player.Color || '#ffffff'
      ctx.globalAlpha = 0.6
      
      player.Territories.forEach(territory => {
        if (!territory.Boundary || territory.Boundary.length < 3) return
        
        ctx.beginPath()
        territory.Boundary.forEach((point, index) => {
          const miniPos = worldToMinimap(point, mapRadius, centerX, centerY)
          if (index === 0) {
            ctx.moveTo(miniPos.x, miniPos.y)
          } else {
            ctx.lineTo(miniPos.x, miniPos.y)
          }
        })
        ctx.closePath()
        ctx.fill()
      })
      
      ctx.globalAlpha = 1.0
    })
    
    // 绘制玩家位置
    gameState.Players.forEach(player => {
      // 兼容CamelCase字段
      const isAlive = player.isAlive !== undefined ? player.isAlive : player.IsAlive
      const currentPosition = player.currentPosition || player.CurrentPosition
      const playerId = player.playerId || player.PlayerId
      const color = player.color || player.Color
      
      if (!isAlive || !currentPosition) return
      
      const miniPos = worldToMinimap(currentPosition, mapRadius, centerX, centerY)
      const isCurrentPlayer = playerId === effectivePlayerId.value
      const radius = isCurrentPlayer ? 4 : 3
      
      // 绘制玩家球
      ctx.fillStyle = color || '#ffffff'
      ctx.beginPath()
      ctx.arc(miniPos.x, miniPos.y, radius, 0, Math.PI * 2)
      ctx.fill()
      
      // 当前玩家额外边框
      if (isCurrentPlayer) {
        ctx.strokeStyle = '#ffffff'
        ctx.lineWidth = 1
        ctx.stroke()
      }
    })
  }
  
  // 绘制道具
  if (gameState.PowerUps) {
    gameState.PowerUps.forEach(powerUp => {
      // 兼容CamelCase字段
      const position = powerUp.position || powerUp.Position
      const powerUpType = powerUp.type || powerUp.Type
      
      if (!position) return
      
      const miniPos = worldToMinimap(position, mapRadius, centerX, centerY)
      
      ctx.fillStyle = getPowerUpColor(powerUpType)
      ctx.beginPath()
      ctx.arc(miniPos.x, miniPos.y, 2, 0, Math.PI * 2)
      ctx.fill()
    })
  }
}

// 世界坐标转小地图坐标
const worldToMinimap = (worldPos, mapRadius, centerX, centerY) => {
  const worldMapRadius = gameState.MapRadius || 1000
  const scale = mapRadius / worldMapRadius
  
  return {
    x: centerX + (worldPos.x - (gameState.MapWidth || 2000) / 2) * scale,
    y: centerY + (worldPos.y - (gameState.MapHeight || 2000) / 2) * scale
  }
}

// 获取道具颜色
const getPowerUpColor = (powerUpType) => {
  const colors = {
    Lightning: '#4FC3F7',  // 蓝色
    Shield: '#FFD700',     // 金色
    Bomb: '#F44336',       // 红色
    Ghost: '#9C27B0'       // 紫色
  }
  return colors[powerUpType] || '#ffffff'
}

// 生命周期
onMounted(async () => {
  // 先初始化用户状态
  try {
    console.log('=== 组件挂载 ===')
    console.log('当前 userStore.userInfo:', userStore.userInfo)
    console.log('当前 userStore.token:', userStore.token)
    
    // 延迟初始化，确保用户状态完全加载
    setTimeout(async () => {
      await initializeGame()
    }, 500)
  } catch (error) {
    console.error('初始化失败:', error)
    connectionError.value = error.message || '初始化失败'
  }
})

onUnmounted(() => {
  lineDrawingGameService.disconnect()
  // 移除键盘事件监听
  document.removeEventListener('keydown', handleKeyPress)
})

// 添加键盘事件监听
onMounted(() => {
  document.addEventListener('keydown', handleKeyPress)
})
</script>

<style scoped>
/* 主容器 */
.game-container {
  width: 100vw;
  height: 100vh;
  background: #1a1a2e;
  color: white;
  font-family: 'Arial', sans-serif;
  overflow: hidden;
  position: relative;
}

/* 错误覆盖层 */
.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.error-content {
  background: #2a2a2a;
  padding: 2rem;
  border-radius: 10px;
  text-align: center;
  border: 1px solid #444;
}

.retry-btn {
  margin-top: 1rem;
  padding: 0.7rem 2rem;
  background: #ff4757;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
  transition: background 0.3s;
}

.retry-btn:hover {
  background: #ff3742;
}

/* 游戏界面 */
.game-interface {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 主游戏区域 */
.game-main {
  flex: 1;
  display: flex;
  position: relative;
  height: 100vh;
}

/* 左侧边栏 */
.left-sidebar {
  width: 200px;
  background: rgba(0, 0, 0, 0.3);
  border-right: 1px solid #333;
  display: flex;
  flex-direction: column;
}

.leaderboard {
  flex: 1;
  padding: 15px;
}

.panel-title {
  font-size: 1.1rem;
  margin: 0 0 15px 0;
  text-align: center;
  color: #fff;
  border-bottom: 1px solid #444;
  padding-bottom: 8px;
}

.leaderboard-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.leaderboard-item {
  display: flex;
  align-items: center;
  padding: 8px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
  font-size: 0.85rem;
  border: 1px solid transparent;
  transition: all 0.2s;
}

.leaderboard-item:hover {
  background: rgba(255, 255, 255, 0.1);
}

.leaderboard-item.current-player {
  background: rgba(74, 144, 226, 0.3);
  border-color: #4a90e2;
}

.leaderboard-item.dead-player {
  opacity: 0.6;
  background: rgba(255, 0, 0, 0.1);
}

.player-rank {
  width: 18px;
  height: 18px;
  background: #333;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.75rem;
  font-weight: bold;
  margin-right: 8px;
  min-width: 18px;
}

.player-avatar {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  border: 1px solid rgba(255, 255, 255, 0.4);
  margin-right: 6px;
  min-width: 12px;
}

.player-info {
  flex: 1;
  min-width: 0;
}

.player-name {
  font-size: 0.8rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.player-score {
  font-size: 0.75rem;
  color: #ccc;
}

.player-percent {
  font-size: 0.8rem;
  font-weight: bold;
  color: #4CAF50;
  margin-left: 4px;
}

/* 左侧小地图容器 */
.left-minimap-container {
  padding: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-top: 1px solid #444;
}

.left-minimap {
  position: relative;
  width: 100%;
  height: 160px;
  background: #2a2a2a;
  border: 2px solid #ff6b6b;
  border-radius: 50%;
  overflow: hidden;
}

.left-minimap-canvas {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  cursor: pointer;
}

/* 画布区域 */
.canvas-area {
  flex: 1;
  position: relative;
  background: #16213e;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  min-height: calc(100vh - 40px);
}

.main-canvas {
  width: 100%;
  height: 100%;
  max-width: 1600px;
  max-height: 1000px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6);
  border: 2px solid rgba(255, 255, 255, 0.1);
}

/* 错误提示 */
.error-toast {
  position: fixed;
  top: 20px;
  right: 20px;
  background: rgba(231, 76, 60, 0.95);
  color: white;
  padding: 12px 20px;
  border-radius: 8px;
  backdrop-filter: blur(10px);
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 10px;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.toast-close {
  background: transparent;
  border: none;
  color: white;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.2s;
}

.toast-close:hover {
  background: rgba(255, 255, 255, 0.2);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .left-sidebar {
    width: 180px;
  }
}

@media (max-width: 900px) {
  .game-main {
    flex-direction: column;
  }
  
  .left-sidebar {
    width: 100%;
    height: 120px;
    flex-direction: row;
    border-right: none;
    border-bottom: 1px solid #333;
  }
}

@media (max-width: 600px) {
  .game-title {
    font-size: 1.4rem;
  }
}
</style>